/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.prapps.chess.client.tcp.ui;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.util.logging.Logger;

import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import com.prapps.chess.client.tcp.cb.ClientController;
import com.prapps.chess.client.tcp.cb.ServerConnector;
import com.prapps.chess.client.tcp.cb.ServerDetails;
import com.prapps.chess.client.tcp.ui.thread.EngineStatusThread;
import com.prapps.chess.common.engines.ProtocolConstants;
import com.prapps.chess.uci.share.NetworkRW;

/**
 *
 * @author pratik
 */
public class TCPClientUtil extends javax.swing.JFrame {

	private static final Logger LOG = Logger.getLogger(TCPClientUtil.class.getName());

	private ClientController controller;
	/**
	 * Creates new form TCPClientUtil
	 */
	public TCPClientUtil() {
		System.getProperties().put("java.util.logging.config.file", "logging.properties");
		LOG.info("log level: " + LOG.getLevel());
		threadRW = new ThreadRW();
		initComponents();
		ButtonCellRenderer renderer = new ButtonCellRenderer();
		tblServerDetails.getColumnModel().getColumn(3).setCellRenderer(renderer);
		tblServerDetails.getColumnModel().getColumn(3).setCellEditor(renderer);
		tblServerDetails.setCellSelectionEnabled(true);
		tblServerDetails.addMouseListener(new MouseListener() {
			
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			public void mouseClicked(MouseEvent e) {
				int row = tblServerDetails.getSelectedRow();
				int col = tblServerDetails.getSelectedColumn();
				if(col == 3) {
					String serverId = (String) ((DefaultTableModel)tblServerDetails.getModel()).getValueAt(row, col-3);
					try {
						controller.retartServer(serverId);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
		});
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		centerPanel = new javax.swing.JPanel();
		jScrollPane1 = new javax.swing.JScrollPane();
		tblServerDetails = new javax.swing.JTable();
		lblServerDetails = new javax.swing.JLabel();
		lblStatus = new javax.swing.JLabel();
		cmdShutDown = new javax.swing.JButton();
		cmdRefresh = new javax.swing.JButton();
		connectionPanel = new javax.swing.JPanel();
		cmdConnect = new javax.swing.JButton();
		txtUsername = new javax.swing.JTextField();
		txtPassword = new javax.swing.JTextField();
		lblUsername = new javax.swing.JLabel();
		lblPassword = new javax.swing.JLabel();
		cmdDisconnect = new javax.swing.JButton();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		setTitle("TCP Client Util");

		centerPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

		tblServerDetails.setModel(new javax.swing.table.DefaultTableModel(new Object[][] { { null, null, null, null } }, new String[] { "Engine Name",
				"Port Number", "Status", "Restart" }) {
			Class[] types = new Class[] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class };
			boolean[] canEdit = new boolean[] { false, false, false, true };

			public Class getColumnClass(int columnIndex) {
				return types[columnIndex];
			}

			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit[columnIndex];
			}
		});
		jScrollPane1.setViewportView(tblServerDetails);

		lblServerDetails.setText("Server Details");

		lblStatus.setText("Status: ");

		cmdShutDown.setText("Shut Down PC");
		cmdShutDown.setEnabled(false);
		cmdShutDown.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				cmdShutDownActionPerformed(evt);
			}
		});

		cmdRefresh.setText("Refresh");
		cmdRefresh.setEnabled(false);
		cmdRefresh.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				cmdRefreshActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout centerPanelLayout = new javax.swing.GroupLayout(centerPanel);
		centerPanel.setLayout(centerPanelLayout);
		centerPanelLayout.setHorizontalGroup(centerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addGroup(
				centerPanelLayout
						.createSequentialGroup()
						.addContainerGap()
						.addGroup(
								centerPanelLayout
										.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
										.addGroup(
												centerPanelLayout
														.createSequentialGroup()
														.addGroup(
																centerPanelLayout
																		.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
																		.addComponent(lblServerDetails, javax.swing.GroupLayout.Alignment.LEADING,
																				javax.swing.GroupLayout.PREFERRED_SIZE, 327,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING,
																				javax.swing.GroupLayout.PREFERRED_SIZE, 327,
																				javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(0, 0, Short.MAX_VALUE))
										.addGroup(
												javax.swing.GroupLayout.Alignment.TRAILING,
												centerPanelLayout
														.createSequentialGroup()
														.addGap(0, 0, Short.MAX_VALUE)
														.addGroup(
																centerPanelLayout
																		.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
																		.addComponent(lblStatus, javax.swing.GroupLayout.Alignment.TRAILING,
																				javax.swing.GroupLayout.PREFERRED_SIZE, 327,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addGroup(
																				javax.swing.GroupLayout.Alignment.TRAILING,
																				centerPanelLayout.createSequentialGroup().addComponent(cmdRefresh)
																						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																						.addComponent(cmdShutDown))))).addContainerGap()));
		centerPanelLayout.setVerticalGroup(centerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				javax.swing.GroupLayout.Alignment.TRAILING,
				centerPanelLayout
						.createSequentialGroup()
						.addContainerGap()
						.addComponent(lblStatus)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
						.addComponent(lblServerDetails)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(
								centerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(cmdShutDown)
										.addComponent(cmdRefresh)).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

		connectionPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

		cmdConnect.setText("Connect");
		cmdConnect.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				cmdConnectActionPerformed(evt);
			}
		});

		lblUsername.setText("User Name: ");

		lblPassword.setText("Password: ");

		cmdDisconnect.setText("Disconnect");
		cmdDisconnect.setEnabled(false);
		cmdDisconnect.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				cmdDisconnectActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout connectionPanelLayout = new javax.swing.GroupLayout(connectionPanel);
		connectionPanel.setLayout(connectionPanelLayout);
		connectionPanelLayout.setHorizontalGroup(connectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				connectionPanelLayout
						.createSequentialGroup()
						.addContainerGap()
						.addGroup(
								connectionPanelLayout
										.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
										.addGroup(
												connectionPanelLayout.createSequentialGroup().addComponent(cmdDisconnect)
														.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(cmdConnect))
										.addGroup(
												connectionPanelLayout
														.createSequentialGroup()
														.addComponent(lblUsername)
														.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
														.addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 224,
																javax.swing.GroupLayout.PREFERRED_SIZE))
										.addGroup(
												connectionPanelLayout
														.createSequentialGroup()
														.addComponent(lblPassword)
														.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
														.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 225,
																javax.swing.GroupLayout.PREFERRED_SIZE))).addContainerGap(18, Short.MAX_VALUE)));
		connectionPanelLayout.setVerticalGroup(connectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				javax.swing.GroupLayout.Alignment.TRAILING,
				connectionPanelLayout
						.createSequentialGroup()
						.addContainerGap()
						.addGroup(
								connectionPanelLayout
										.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
										.addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
												javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(lblUsername))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(
								connectionPanelLayout
										.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
										.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
												javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(lblPassword))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(
								connectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(cmdConnect)
										.addComponent(cmdDisconnect)).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				layout.createSequentialGroup()
						.addContainerGap()
						.addGroup(
								layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
										.addComponent(centerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addComponent(connectionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
												javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(0, 9, Short.MAX_VALUE)));
		layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				javax.swing.GroupLayout.Alignment.TRAILING,
				layout.createSequentialGroup()
						.addContainerGap()
						.addComponent(connectionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.PREFERRED_SIZE)
						.addGap(18, 18, 18)
						.addComponent(centerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(16, Short.MAX_VALUE)));

		pack();
	}// </editor-fold>

	private void cmdConnectActionPerformed(java.awt.event.ActionEvent evt) {

		Thread t = new Thread(new Runnable() {
			public void run() {
				ServerConnector connector = null;
				try {
					connector = ServerConnector.getInstance();
				} catch (IOException ex) {
					LOG.warning(ex.getMessage());
					OKCancelDialog okCancelDialog = new OKCancelDialog(getMe(), true);
					okCancelDialog.setVisible(true);
					String ip = okCancelDialog.getIP();
					int port = okCancelDialog.getPort();
					try {
						connector = ServerConnector.getInstance();
						connector.connect(ip, port);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (connector.isConnected()) {
					handleConnected();
				}
				try {
					connector.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		});
		t.start();

	}

	private void cmdDisconnectActionPerformed(java.awt.event.ActionEvent evt) {
		controller.disconnect();
		clearTable();
		lblStatus.setText("Status: Disconnected");
	}

	private void cmdRefreshActionPerformed(java.awt.event.ActionEvent evt) {
		new Thread(new EngineStatusThread((DefaultTableModel) tblServerDetails.getModel())).start();
	}

	private void cmdShutDownActionPerformed(java.awt.event.ActionEvent evt) {
		try {
			controller.shutDown();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private TCPClientUtil getMe() {
		return this;
	}

	private void handleConnected() {
		try {
			ServerDetails serverDetails = controller.getAvailableServers();
			lblStatus.setText("Status: " + " Connected");
			DefaultTableModel tableModel = (DefaultTableModel) tblServerDetails.getModel();
			for (int i = 0; i < tableModel.getRowCount(); i++) {
				tableModel.removeRow(i);
			}
			for (String[] server : serverDetails.getServers()) {
				tableModel.addRow(server);
			}
			cmdDisconnect.setEnabled(true);
			cmdRefresh.setEnabled(true);
			cmdShutDown.setEnabled(true);

			engineStatusThread = new Thread(new EngineStatusThread((DefaultTableModel) tblServerDetails.getModel()));
			engineStatusThread.start();
		} catch (IOException e) {
			e.printStackTrace();
			lblStatus.setText(lblStatus.getText() + " Connection Error");
		}
	}

	public void setController(ClientController controller) {
		this.controller = controller;
	}
	
	public void clearTable() {
		while(tblServerDetails.getModel().getRowCount() > 0) {
			((DefaultTableModel)tblServerDetails.getModel()).removeRow(0);
		}
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		// <editor-fold defaultstate="collapsed"
		// desc=" Look and feel setting code (optional) ">
		/*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the
		 * default look and feel. For details see
		 * http://download.oracle.com/javase
		 * /tutorial/uiswing/lookandfeel/plaf.html
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(TCPClientUtil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(TCPClientUtil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(TCPClientUtil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(TCPClientUtil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		// </editor-fold>

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
			
				TCPClientUtil tcpClientUtil = new TCPClientUtil();
				tcpClientUtil.setVisible(true);
				ClientController controller = new ClientController(tcpClientUtil);
				tcpClientUtil.setController(controller);
			}
		});
	}

	// Variables declaration - do not modify
	private javax.swing.JPanel centerPanel;
	private javax.swing.JButton cmdConnect;
	private javax.swing.JButton cmdDisconnect;
	private javax.swing.JButton cmdRefresh;
	private javax.swing.JButton cmdShutDown;
	private javax.swing.JPanel connectionPanel;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JLabel lblPassword;
	private javax.swing.JLabel lblServerDetails;
	private javax.swing.JLabel lblStatus;
	private javax.swing.JLabel lblUsername;
	private javax.swing.JTable tblServerDetails;
	private javax.swing.JTextField txtPassword;
	private javax.swing.JTextField txtUsername;
	// End of variables declaration

	private ServerConnector connector;
	private ThreadRW threadRW;
	private Thread engineStatusThread;

}
